package com.cn.http.service.impl;

import cn.com.allunion.sms.pojo.Smsrecord;
import com.alibaba.fastjson.JSON;
import com.cn.http.service.AbstractSmsSendService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 联通短信发送服务，发送号码处理（例如：是否要在电话号码前加86）由实现端来处理
 * Created by YangJie on 2016/4/21.
 */
public class UnicomSmsSendService extends AbstractSmsSendService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UnicomSmsSendService.class) ;

    /**
     * 电话号码前缀
     */
    protected final String phoneNumberPrefix ;

    /**
     * 电话号码群发分隔符
     */
    protected final String phoneNumberGroupSeparator ;

    public UnicomSmsSendService(String phoneNumberPrefix, String phoneNumberGroupSeparator) {
        this.phoneNumberPrefix = phoneNumberPrefix ;
        this.phoneNumberGroupSeparator = phoneNumberGroupSeparator ;
    }

    @Override
    public String send(List<Smsrecord> smsRecords) {


        if (smsRecords == null || smsRecords.size() == 0) {
            return "sms记录为空";
        }

        // 单发短信功能
        String result = null;
        for (Smsrecord sRecord : smsRecords) {
            String rlt = smsrecordService.addNewRecord(sRecord);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("短信记录ID: {}", sRecord.getSmsRecordID());
                LOGGER.debug("短信单发电话号码处理前: {}", sRecord.getSendNumber());
            }

            if (rlt.equals("success")) {
                // 发送消息到消息队列
                String message = getSendMessage(sRecord, sRecord.getSmsBusinessRecord().getBusinessSignature()) ;
                if(LOGGER.isDebugEnabled()) {
                    LOGGER.debug("message： {}", message);
                }

                // 发送消息到消息队列
                if (StringUtils.isNotEmpty(message)) {
                    sendSMS.send(message);
                    result = "接收成功！";
                } else {
                    result = "接收失败，无法获取转换后的消息， smsrecord: " + JSON.toJSONString(sRecord);
                }
            } else {
                result = "发送之前存储失败";
                LOGGER.debug("发送之前存储失败");
            }
        }
        return result;
    }

    /**
     * 电话号码处理方法
     *
     * @param param 处理格式 比如加86
     * @param tels 待处理的电话号码
     * @param separetor 分隔符
     * @return 处理后的电话号码
     */
    private String dealTels(String param, String tels, String separetor) {
        tels = param + tels;
        tels = tels.replace(separetor, separetor + param);

        return tels;
    }

    public String getPhoneNumberPrefix() {
        return phoneNumberPrefix;
    }
}
